package com.jake.springboot.mybatis.handler;

import com.alibaba.fastjson.JSON;
import com.jake.springboot.mybatis.domain.PersonJson;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(PersonJson.class)
@MappedJdbcTypes(JdbcType.OTHER)
public class PersonJsonHandler extends BaseTypeHandler<PersonJson> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, PersonJson parameter, JdbcType jdbcType) throws SQLException {
//        preparedStatement.setObject(i, personJson);
        ps.setString(i, JSON.toJSONString(parameter));
    }

    @Override
    public PersonJson getNullableResult(ResultSet rs, String columnName) throws SQLException {
//        return rs.getObject(columnName, PersonJson.class);
        String personJsonStr = rs.getString(columnName);
        return JSON.parseObject(personJsonStr, PersonJson.class);
    }

    @Override
    public PersonJson getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String personJsonStr = resultSet.getString(columnIndex);
        return JSON.parseObject(personJsonStr, PersonJson.class);
    }

    @Override
    public PersonJson getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String personJsonStr = cs.getString(columnIndex);
        return JSON.parseObject(personJsonStr, PersonJson.class);
    }
}
